/**
 * @author: tjp
 * @create: 2023-04-03 11:22
 * @Description: Socket客户端
 */
export class WebSocketClient {
  constructor(userId) {
    this.userId = userId;
    this.websocket = null;
    this.timeout = 10000; // 心跳超时时间，单位ms
    this.timeoutObj = null; // 心跳定时器
    this.serverTimeoutObj = null; // 服务器超时定时器
    this.lockReconnect = false; // 避免重复连接
    this.timeoutnum = null; // 重连延迟定时器
  }

  // 初始化WebSocket连接
  initWebSocket() {
    if(!('WebSocket' in window)) {
      alert("该浏览器不支持websocket！");
    }else {
      // let wsUrl = `/websocket/${this.userId}`;
      let wsUrl = `ws://${import.meta.env.VITE_APP__SOCKET_PATH}`
      console.log(wsUrl);
      if ( this.websocket != null) {
        this.websocket.close();
        this.websocket = null;
      }
      this.websocket = new WebSocket(`ws://${import.meta.env.VITE_APP__SOCKET_PATH}${this.userId}`);

      // this.websocket = new WebSocket(wsUrl);
      console.log("this.websocket===>",this.websocket);
      this.websocket.onopen = this.websocketonopen.bind(this);
      this.websocket.onerror = this.websocketonerror.bind(this);
      this.websocket.onmessage = this.setOnmessageMessage.bind(this);
      this.websocket.onclose = this.websocketclose.bind(this);
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.websocketclose.bind(this);
    }
  }

  // 启动心跳
  start() {
    console.log('start');
    // 清除延时器
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    // 向服务器发送心跳消息
    let actions = { "test": "12345" };
    this.websocket && this.websocket.readyState == 1 && this.websocket.send(JSON.stringify(actions));
    // 启动心跳定时器
    this.timeoutObj = setTimeout(() => {
      this.start();
      // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
      this.serverTimeoutObj = setTimeout(() => {
        this.websocket.close();
      }, this.timeout)
    }, this.timeout)
  }

  // 重置心跳
  reset() {
    // 清除时间
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    // 重启心跳
    this.start();
  }

  // 重新连接
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    this.timeoutnum && clearTimeout(this.timeoutnum);
    this.timeoutnum = setTimeout(() => {
      this.initWebSocket();
      this.lockReconnect = false;
    }, 5000)
  }

  // 处理收到的消息
  async setOnmessageMessage(event) {
    console.log(event.data, '获得消息');
    // 重置心跳
    this.reset();
    // 自定义全局监听事件
    window.dispatchEvent(new CustomEvent('onmessageWS', {
      detail: {
        data: event.data
      }
    }))
    // //发现消息进入    开始处理前端触发逻辑
    // if (event.data === 'success' || event.data === 'heartBath') return
  }

  // WebSocket连接成功回调
  websocketonopen() {
    // 开启心跳
    this.start();
    console.log("WebSocket连接成功!!!" + new Date() + "----" + this.websocket.readyState);
    clearInterval(this.otimer);//停止
  }

  // WebSocket连接错误回调
  websocketonerror(e) {
    console.log("WebSocket连接发生错误" + JSON.stringify(e));
  }

  // WebSocket连接关闭回调
  websocketclose(e) {
    this.websocket.close();
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    console.log("websocketcloe关闭连接")
  }

  // 关闭WebSocket连接
  closeWebSocket() {
    this.websocket.close();
    console.log("closeWebSocket关闭连接")
  }

  // 监听窗口关闭事件
  onbeforeunload() {
    this.closeWebSocket();
  }
}
